function selectDate(button){
	var btnId = button.id;
	$("#datePicker_"+btnId).datepicker({
			onSelect:function(dateString,datePicker){
				var timeString = convertTimeString(dateString);
				if(!isEarlierThanToday(dateString)){
					placeOrder(timeString,btnId);
					$("#datePicker_"+btnId).hide();
				}else{
					alert("Please select a date later than today");
				}
			}
	});
}

function convertTimeString(dateString){
	var month = dateString.substring(0,2);
	var date = dateString.substring(3,5);
	var year = dateString.substring(6,10);
	
	var result = year+"-"+month+"-"+date;
	return result;
}

function isEarlierThanToday(dateString){
	var date = convertToDateObject(dateString);
	var today = new Date();
	return date<today;
}

function convertToDateObject(dateString){
	var month = dateString.substring(0,2);
	var date = dateString.substring(3,5);
	var year = dateString.substring(6,10);

	var result = new Date(parseInt(year),parseInt(month)-1,parseInt(date));
	return result;
}

function placeOrder(timeString,address){
	var userName = getCookies();
	var len = userName.length;
	userName = userName.substring(0,len-2);
	var email = "";

	$.post("http://localhost/cs2102/src/getInfo.php",
	{
		name:userName
	},
	function(dataJson,status){
		var len2 = dataJson.length;
		var dat = $.parseJSON(dataJson.substring(1,len2-1));
		email = dat["email"];

		address = address.split("_").join(" ");

		// alert(address);
		// alert(email);
		// alert(timeString);

		$.post("http://localhost/cs2102/src/placeOrder.php",
		{
			email:email,
			address:address,
			arrivalTime:timeString
		},function(dataJson,status){
			if(dataJson == "Success"){
				alert("Order Successful");
				window.location.href = "index.html";
			}else{
				alert("Order Failed");
			}
		});
	});
}